import React, { useEffect, useRef, useState } from "react";
import axios from "axios";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
    Terminal, Search, Hash, Users, Archive, Clock,
    Eye, Edit3, ChevronLeft, ChevronRight, Cpu,
    Zap, Layout, ArrowUpRight
} from 'lucide-react';
import {api} from "./api/request";

// --- 1. 配置與 API 模塊 (Inline Integration) ---

// 由於缺少 ../config 文件，這裡暫時定義一個變量，請替換為您真實的 API 地址
// const basicUrlDev = "https://api.jiangyuan.blog";
//
// const api = axios.create({
//     baseURL: basicUrlDev,
//     timeout: 10000,
// });
//
// api.interceptors.request.use(config => {
//     const token = localStorage.getItem('token');
//     if (token) {
//         config.headers.Authorization = token;
//     }
//     return config;
// });
//
// api.interceptors.response.use(
//     res => res,
//     err => {
//         if (err.response?.status === 401) {
//             localStorage.removeItem('token');
//             // 在單頁應用中，通常使用路由跳轉，這裡保留您原始的邏輯
//             window.location.href = '/login';
//         }
//         return Promise.reject(err);
//     }
// );

// --- 2. MarkdownIframe 組件 (Inline Integration) ---

interface MarkdownIframeProps {
    content: string;
}

const MarkdownIframe: React.FC<MarkdownIframeProps> = ({ content }) => {
    const iframeRef = useRef<HTMLIFrameElement>(null);
    const [height, setHeight] = useState(0);

    useEffect(() => {
        if (iframeRef.current) {
            const iframe = iframeRef.current;
            const doc = iframe.contentDocument;

            if (doc) {
                doc.open();
                doc.write(`
                    <html>
                        <head>
                            <style>
                                body {
                                    font-family: 'Courier New', Courier, monospace; /* 調整字體以匹配賽博風格 */
                                    color: #e5e7eb;
                                    background-color: transparent; /* 透明背景以融入主設計 */
                                    padding: 0;
                                    line-height: 1.8;
                                    margin: 0;
                                    overflow-y: hidden;
                                }
                                h1 { font-size: 2em; margin: 0.67em 0; color: #ffffff; border-bottom: 1px solid #333; padding-bottom: 0.3em; }
                                h2 { font-size: 1.5em; margin: 0.75em 0; color: #ccff00; } /* 標題使用酸性綠 */
                                h3 { font-size: 1.2em; margin: 0.85em 0; color: #d946ef; } /* 標題使用電光紫 */
                                p { margin: 0.5em 0; }
                                a { color: #ccff00; text-decoration: none; border-bottom: 1px dashed #ccff00; }
                                code { background-color: #1a1a1a; color: #ccff00; padding: 2px 6px; border-radius: 4px; font-family: monospace; border: 1px solid #333; }
                                pre { background-color: #0a0a0a; color: #f0f0f0; padding: 16px; border-radius: 8px; overflow-x: auto; border: 1px solid #333; }
                                table { border-collapse: collapse; margin: 1em 0; width: 100%; }
                                th, td { border: 1px solid #333; padding: 8px 12px; text-align: left; }
                                th { background-color: #1a1a1a; color: #ccff00; }
                                blockquote { border-left: 4px solid #d946ef; padding-left: 16px; color: #9ca3af; margin: 1em 0; background: rgba(217, 70, 239, 0.05); py: 4px; }
                                ul { padding-left: 1.2em; list-style-type: square; color: #d946ef; }
                                ul li span { color: #e5e7eb; }
                                ol { padding-left: 1.2em; list-style-type: decimal; color: #ccff00; }
                                img { max-width: 100%; border-radius: 8px; border: 1px solid #333; }
                            </style>
                        </head>
                        <body>
                            <div id="root"></div>
                            <script>
                                function updateHeight() {
                                    const height = document.body.scrollHeight;
                                    window.parent.postMessage({ type: 'setHeight', height }, '*');
                                }
                                window.addEventListener('load', updateHeight);
                                window.addEventListener('resize', updateHeight);
                                // 監聽圖片加載完成後更新高度
                                const imgs = document.getElementsByTagName('img');
                                for(let i=0; i<imgs.length; i++) {
                                    imgs[i].onload = updateHeight;
                                }
                                // 定時檢查高度變化 (防止動態內容)
                                setInterval(updateHeight, 500);
                            </script>
                        </body>
                    </html>
                `);
                doc.close();

                const root = doc.getElementById("root");
                if (root) {
                    import("react-dom").then(ReactDOM => {
                        ReactDOM.render(
                            <ReactMarkdown remarkPlugins={[remarkGfm]}>
                                {content || ""}
                            </ReactMarkdown>,
                            root,
                            () => {
                                // 渲染完成後通知父頁面更新高度
                                setTimeout(() => {
                                    const height = doc.body.scrollHeight;
                                    setHeight(height);
                                }, 100);
                            }
                        );
                    });
                }
            }
        }

        // 監聽 iframe 發送的消息
        const handleMessage = (event: MessageEvent) => {
            if (event.data?.type === "setHeight" && typeof event.data.height === "number") {
                setHeight(event.data.height);
            }
        };
        window.addEventListener("message", handleMessage);

        return () => {
            window.removeEventListener("message", handleMessage);
        };
    }, [content]);

    return (
        <iframe
            ref={iframeRef}
            title="Markdown Content"
            style={{ width: "100%", height: `${height}px`, border: "none", overflow: "hidden" }}
        />
    );
};


// --- 3. 頁面邏輯與 UI (BlogViewPage) ---

interface BlogModel {
    id: number;
    articleName: string;
    name: string;
    content: string;
    createTime: string;
    readCount?: number;
    author?: string;
    category?: string;
}

interface ArticleModel extends BlogModel {}

// 裝飾性組件：故障文字
const GlitchText = ({ text, active = false }: { text: string, active?: boolean }) => (
    <div className="relative inline-block group">
    <span className={`relative z-10 font-black tracking-tighter ${active ? 'text-[#ccff00]' : 'text-white group-hover:text-[#ccff00]'} transition-colors`}>
      {text}
    </span>
        {active && (
            <>
                <span className="absolute top-0 left-0 -ml-0.5 translate-x-[2px] text-[#d946ef] opacity-100 animate-pulse z-0 mix-blend-screen">{text}</span>
                <span className="absolute top-0 left-0 -ml-0.5 -translate-x-[2px] text-cyan-400 opacity-100 animate-pulse delay-75 z-0 mix-blend-screen">{text}</span>
            </>
        )}
    </div>
);

// 裝飾性組件：環境光暈
const AmbientLight = () => {
    const [mousePos, setMousePos] = useState({ x: 0, y: 0 });
    useEffect(() => {
        const handleMouseMove = (e: MouseEvent) => setMousePos({ x: e.clientX, y: e.clientY });
        window.addEventListener('mousemove', handleMouseMove);
        return () => window.removeEventListener('mousemove', handleMouseMove);
    }, []);
    return (
        <div
            className="fixed w-[500px] h-[500px] bg-[#d946ef]/10 rounded-full blur-[100px] pointer-events-none z-0 mix-blend-screen transition-transform duration-100 ease-out will-change-transform"
            style={{ left: mousePos.x - 250, top: mousePos.y - 250 }}
        />
    );
};

const BlogViewPage = () => {
    const [blogs, setBlogs] = useState<BlogModel[]>([]);
    const [formData, setFormData] = useState({ pageNum: 1, pageSize: 10 });
    const [total, setTotal] = useState(0);
    const [selectedArticle, setSelectedArticle] = useState<ArticleModel | null>(null);
    const [loading, setLoading] = useState(false);
    const [sidebarVisible, setSidebarVisible] = useState(true);
    const [activeNav, setActiveNav] = useState('首頁');

    const fetchBlogs = async () => {
        try {
            const res = await api.post("blogs/view/page", formData);
            // 兼容不同的後端返回結構，嘗試讀取 res.data.data 或 res.data
            const data = res.data?.data || res.data;
            if (data && (data.records || Array.isArray(data))) {
                setBlogs(data.records || data);
                setTotal(data.total || 0);
            }
        } catch (error) {
            console.error("獲取博客列表失敗:", error);
        }
    };

    const fetchArticleDetail = async (id: number) => {
        setLoading(true);
        try {
            const res = await api.get(`article/view/get`, { params: { id } });
            const data = res.data?.data || res.data;
            setSelectedArticle(data);
        } catch (error) {
            console.error("獲取文章詳情失敗:", error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchBlogs();
    }, [formData]);

    const navItems = [
        { name: '首頁', icon: Terminal },
        { name: '熱榜', icon: Zap },
        { name: '分類', icon: Layout },
        { name: '歸檔', icon: Archive },
        { name: '標籤', icon: Hash },
        { name: '朋友', icon: Users },
        { name: '關於', icon: Cpu },
    ];

    return (
        <div className="flex min-h-screen w-full bg-[#050505] text-gray-200 font-mono selection:bg-[#ccff00] selection:text-black overflow-hidden relative">

            <AmbientLight />

            {/* 網格背景 */}
            <div className="fixed inset-0 bg-[linear-gradient(to_right,#80808008_1px,transparent_1px),linear-gradient(to_bottom,#80808008_1px,transparent_1px)] bg-[size:24px_24px] pointer-events-none z-0"></div>

            {/* 側邊欄 */}
            <aside
                className={`relative z-20 flex flex-col border-r border-white/10 bg-[#0a0a0a]/80 backdrop-blur-xl transition-all duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] ${
                    sidebarVisible ? "w-72 translate-x-0" : "w-0 -translate-x-20 opacity-0 overflow-hidden border-none"
                }`}
            >
                <div className="p-8">
                    <h1 className="text-3xl font-black tracking-tighter text-white mb-2 flex items-center gap-2">
                        <span className="text-[#ccff00]">{`{`}</span>
                        <GlitchText text="YUAN.LOG" active />
                        <span className="text-[#ccff00]">{`}`}</span>
                    </h1>
                    <p className="text-xs text-gray-500 uppercase tracking-widest mb-10">/// System Online</p>

                    <nav className="flex flex-col space-y-2">
                        {navItems.map((item) => (
                            <button
                                key={item.name}
                                onClick={() => setActiveNav(item.name)}
                                className={`group flex items-center gap-4 px-4 py-3 rounded-lg transition-all duration-300 border ${
                                    activeNav === item.name
                                        ? 'bg-white/5 border-[#ccff00]/30 text-[#ccff00]'
                                        : 'border-transparent hover:bg-white/5 hover:border-white/10 text-gray-400 hover:text-white'
                                }`}
                            >
                                <item.icon size={18} className={activeNav === item.name ? 'animate-pulse' : ''} />
                                <span className="font-bold tracking-wide">{item.name}</span>
                                {activeNav === item.name && <ChevronRight size={14} className="ml-auto" />}
                            </button>
                        ))}
                    </nav>
                </div>

                <div className="mt-auto p-8 border-t border-white/5">
                    <div className="flex items-center gap-2 px-4 py-3 bg-black/40 border border-white/10 rounded-lg text-gray-500 focus-within:border-[#d946ef] focus-within:text-[#d946ef] transition-colors">
                        <Search size={16} />
                        <input
                            type="text"
                            placeholder="SEARCH_LOGS..."
                            className="bg-transparent border-none outline-none w-full text-sm placeholder-gray-600"
                        />
                    </div>
                </div>
            </aside>

            {/* 懸浮切換按鈕 */}
            <button
                onClick={() => setSidebarVisible(!sidebarVisible)}
                className={`fixed top-1/2 transition-all duration-500 z-30 group
                    ${sidebarVisible ? "left-72" : "left-0"} 
                    -translate-y-1/2 w-6 h-24 bg-[#0a0a0a] border-y border-r border-white/10 rounded-r-xl flex items-center justify-center hover:bg-[#ccff00] hover:text-black text-gray-500 cursor-pointer`}
            >
                <div className="w-1 h-8 bg-current rounded-full group-hover:h-12 transition-all"></div>
            </button>

            {/* 主內容區域 */}
            <main className="flex-1 relative z-10 flex flex-col h-screen overflow-hidden">

                {/* 頂部狀態欄 */}
                <header className="h-16 border-b border-white/5 flex items-center justify-between px-8 bg-[#050505]/50 backdrop-blur-sm">
                    <div className="flex items-center gap-4 text-xs font-bold text-gray-500">
                        <span className="flex items-center gap-1"><div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div> LIVE</span>
                        <span className="text-[#d946ef]">:: ROOT/BLOG/VIEW</span>
                    </div>
                    <div className="text-xs text-gray-600 font-mono">
                        RAM: 42% // CPU: 12%
                    </div>
                </header>

                <div className="flex-1 overflow-auto p-8 md:p-12 scroll-smooth custom-scrollbar">
                    {!selectedArticle ? (
                        <div className="max-w-5xl mx-auto animate-in fade-in slide-in-from-bottom-8 duration-700">
                            {/* 列表頭部 */}
                            <div className="mb-12 flex items-end justify-between">
                                <div>
                                    <h2 className="text-5xl font-black text-white mb-2 tracking-tighter">LATEST_TRANSMISSIONS</h2>
                                    <p className="text-[#ccff00] font-mono text-sm">/// EXPLORING THE DIGITAL FRONTIER</p>
                                </div>
                                <div className="hidden md:block text-right text-xs text-gray-500 font-mono border-l border-[#d946ef] pl-4">
                                    TOTAL_LOGS: {total}<br/>
                                    PAGE: {formData.pageNum}
                                </div>
                            </div>

                            {/* 博客列表 */}
                            <div className="grid gap-6">
                                {blogs.map((blog, index) => (
                                    <div
                                        key={blog.id}
                                        className="group relative bg-[#0a0a0a] border border-white/10 p-8 transition-all duration-300 hover:border-[#ccff00] hover:-translate-y-1 cursor-pointer overflow-hidden"
                                        onClick={() => fetchArticleDetail(blog.id)}
                                        style={{ animationDelay: `${index * 50}ms` }}
                                    >
                                        <div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-[#ccff00]/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>

                                        <div className="flex flex-col md:flex-row justify-between gap-6 relative z-10">
                                            <div className="flex-1">
                                                <div className="flex items-center gap-3 text-xs font-bold text-gray-500 mb-3">
                                                    <span className="px-2 py-0.5 bg-white/5 text-[#d946ef] rounded border border-white/5">
                                                        LOG_#{blog.name}
                                                    </span>
                                                    <span className="flex items-center gap-1"><Clock size={12} /> {blog.createTime}</span>
                                                </div>

                                                <h3 className="text-2xl font-bold text-white mb-3 group-hover:text-[#ccff00] transition-colors">
                                                    {blog.articleName}
                                                </h3>

                                                <p className="text-gray-400 text-sm line-clamp-2 font-mono leading-relaxed max-w-2xl">
                                                    {blog.content?.substring(0, 200) || "No preview available..."}
                                                </p>
                                            </div>

                                            <div className="flex flex-col justify-between items-end gap-4 border-l border-white/5 pl-6 min-w-[140px]">
                                                <div className="text-right space-y-1">
                                                    <div className="flex items-center justify-end gap-2 text-xs text-gray-400">
                                                        <Edit3 size={12} /> {blog.author || 'Unknown'}
                                                    </div>
                                                    <div className="flex items-center justify-end gap-2 text-xs text-gray-400">
                                                        <Eye size={12} /> {blog.readCount || 0} REVIEWS
                                                    </div>
                                                </div>

                                                <button
                                                    onClick={(e) => { e.stopPropagation(); fetchArticleDetail(blog.id); }}
                                                    className="flex items-center gap-2 text-sm font-bold text-white group-hover:text-[#ccff00] transition-colors"
                                                >
                                                    READ_FILE <ArrowUpRight size={16} />
                                                </button>
                                            </div>
                                        </div>

                                        <div className="absolute bottom-0 left-0 w-2 h-2 border-b border-l border-white/30 group-hover:border-[#ccff00] transition-colors"></div>
                                        <div className="absolute top-0 right-0 w-2 h-2 border-t border-r border-white/30 group-hover:border-[#ccff00] transition-colors"></div>
                                    </div>
                                ))}
                            </div>

                            {/* 分頁 */}
                            <div className="flex justify-center mt-12 space-x-2">
                                <button
                                    disabled={formData.pageNum === 1}
                                    onClick={() => setFormData({ ...formData, pageNum: formData.pageNum - 1 })}
                                    className="w-10 h-10 flex items-center justify-center bg-[#0a0a0a] border border-white/10 text-gray-400 hover:border-[#d946ef] hover:text-[#d946ef] disabled:opacity-30 transition-all"
                                >
                                    <ChevronLeft size={16} />
                                </button>
                                {Array.from({ length: Math.min(Math.ceil(total / formData.pageSize) || 1, 5) }, (_, i) => {
                                    const page = i + 1;
                                    return (
                                        <button
                                            key={page}
                                            className={`w-10 h-10 font-mono text-sm border transition-all duration-300 ${
                                                page === formData.pageNum
                                                    ? "bg-[#ccff00] border-[#ccff00] text-black font-black translate-y-[-2px] shadow-[0_4px_0_#d946ef]"
                                                    : "bg-[#0a0a0a] border-white/10 text-gray-400 hover:border-white/30 hover:text-white"
                                            }`}
                                            onClick={() => setFormData({ ...formData, pageNum: page })}
                                        >
                                            {page}
                                        </button>
                                    )
                                })}
                                <button
                                    disabled={formData.pageNum >= Math.ceil(total / formData.pageSize)}
                                    onClick={() => setFormData({ ...formData, pageNum: formData.pageNum + 1 })}
                                    className="w-10 h-10 flex items-center justify-center bg-[#0a0a0a] border border-white/10 text-gray-400 hover:border-[#d946ef] hover:text-[#d946ef] disabled:opacity-30 transition-all"
                                >
                                    <ChevronRight size={16} />
                                </button>
                            </div>
                        </div>
                    ) : (
                        // --- 文章詳情頁 ---
                        <div className="max-w-4xl mx-auto animate-in fade-in zoom-in-95 duration-500">
                            <div className="sticky top-0 z-20 flex justify-between items-center mb-8 bg-[#050505]/80 backdrop-blur-md py-4 border-b border-white/10">
                                <button
                                    onClick={() => setSelectedArticle(null)}
                                    className="group flex items-center gap-2 px-4 py-2 bg-white/5 hover:bg-[#ccff00] hover:text-black text-white rounded transition-all border border-transparent hover:border-[#ccff00]"
                                >
                                    <ChevronLeft size={16} className="group-hover:-translate-x-1 transition-transform" />
                                    <span className="font-mono text-sm font-bold">RETURN_TO_BASE</span>
                                </button>
                                <div className="text-xs font-mono text-gray-500">
                                    READING_MODE: IMMERSIVE
                                </div>
                            </div>

                            {loading ? (
                                <div className="h-64 flex flex-col items-center justify-center text-[#ccff00] font-mono space-y-4">
                                    <Cpu size={48} className="animate-spin" />
                                    <span className="animate-pulse">DECRYPTING_DATA_STREAM...</span>
                                </div>
                            ) : (
                                <article className="bg-[#0a0a0a] border border-white/10 p-1 md:p-2 relative overflow-hidden">
                                    <div className="h-1 w-full bg-gradient-to-r from-[#ccff00] via-[#d946ef] to-[#ccff00] mb-8"></div>

                                    <div className="px-8 pb-12">
                                        <header className="mb-12 text-center">
                                            <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full border border-[#d946ef]/30 bg-[#d946ef]/5 text-[#d946ef] text-xs font-mono mb-6">
                                                {selectedArticle.articleName}
                                            </div>
                                            {/*<h1 className="text-4xl md:text-6xl font-black text-white mb-8 tracking-tighter leading-tight">*/}
                                            {/*    {selectedArticle.articleName}*/}
                                            {/*</h1>*/}

                                            <div className="flex flex-wrap justify-center gap-6 text-sm font-mono text-gray-400 border-y border-white/10 py-4">
                                                <span className="flex items-center gap-2">
                                                    <Edit3 size={14} className="text-[#ccff00]" /> {selectedArticle.author || 'Anonymous'}
                                                </span>
                                                <span className="flex items-center gap-2">
                                                    <Clock size={14} className="text-[#ccff00]" /> {selectedArticle.createTime}
                                                </span>
                                                <span className="flex items-center gap-2">
                                                    <Layout size={14} className="text-[#ccff00]" /> {selectedArticle.content?.length || 0} BYTES
                                                </span>
                                            </div>
                                        </header>

                                        {/* Markdown 內容容器 */}
                                        <div className="prose prose-invert max-w-none">
                                            <div className="rounded-lg border border-white/10 overflow-hidden bg-[#050505]">
                                                {/* 這裡直接使用我們內聯的組件 */}
                                                <MarkdownIframe content={selectedArticle.content || ""} />
                                            </div>
                                        </div>
                                    </div>

                                    <div className="absolute bottom-4 right-4 text-[100px] leading-none font-black text-white/5 select-none pointer-events-none">
                                        EOF
                                    </div>
                                </article>
                            )}
                        </div>
                    )}
                </div>
            </main>

            <style>{`
                .custom-scrollbar::-webkit-scrollbar {
                    width: 6px;
                }
                .custom-scrollbar::-webkit-scrollbar-track {
                    background: #050505;
                }
                .custom-scrollbar::-webkit-scrollbar-thumb {
                    background: #333;
                    border-radius: 3px;
                }
                .custom-scrollbar::-webkit-scrollbar-thumb:hover {
                    background: #ccff00;
                }
            `}</style>
        </div>
    );
};

export default BlogViewPage;